package by.ostrovsky.webhousingsystem.bean.user;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import by.ostrovsky.webhousingsystem.bean.user.form.RegistrationBean;
import by.ostrovsky.webhousingsystem.constants.Constants;
import by.ostrovsky.webhousingsystem.controller.ICheckController;
import by.ostrovsky.webhousingsystem.controller.IUserController;
import by.ostrovsky.webhousingsystem.controller.account.RegistrationController;
import by.ostrovsky.webhousingsystem.controller.validation.CheckForNullFormFieldsController;
import by.ostrovsky.webhousingsystem.controller.validation.LoginCheckInController;
import by.ostrovsky.webhousingsystem.controller.validation.RegistrationValidatorController;
import by.ostrovsky.webhousingsystem.crypt.SHACrypt;
import by.ostrovsky.webhousingsystem.hibernate.entity.Account;

@SuppressWarnings("serial")
public class RegistrationAction extends RegistrationBean {
	private static Logger logger = Logger.getLogger(RegistrationAction.class);

	@Override
	public String execute() {

		ICheckController<Account, Boolean> checkController = new LoginCheckInController();
		ICheckController<RegistrationAction, Boolean> registrationValidatorController = new RegistrationValidatorController();
		ICheckController<RegistrationAction, Boolean> checkForNullFormFieldsController = new CheckForNullFormFieldsController();
		IUserController<Account, Boolean> registrationController = new RegistrationController();

		try {
			Boolean isOk = false;

			// check for empty
			isOk = checkForNullFormFieldsController
					.check(RegistrationAction.this);
			if (!isOk) {
				ServletActionContext.getRequest().setAttribute(Constants.REASON,
						Constants.EMPTY_FIELD);
				return Constants.FAILURE;
			}

			// check for valid
			isOk = registrationValidatorController
					.check(RegistrationAction.this);
			if (!isOk) {
				ServletActionContext.getRequest().setAttribute(Constants.REASON,
						Constants.INCORRECT_REG_DATA);
				return Constants.FAILURE;
			}

			Account account = new Account();
			account.setId(getLogin());

			// check for login existance
			isOk = checkController.check(account);
			if (!isOk) {
				ServletActionContext.getRequest().setAttribute(Constants.REASON,
						Constants.LOGIN_ALREADY_EXISTS);
				return Constants.FAILURE;
			}

			account = new Account();
			account.setId(getLogin());
			account.setHashed(SHACrypt.getInstance().encrypt(getPassword1()));
			account.setUserName(getUsername());
			account.setMail(getMail());
			account.setAccessLevel(0);
			// do registration
			isOk = registrationController.registrate(account);
			if (isOk) {
				ServletActionContext.getRequest().setAttribute(Constants.SUCCESS,
						Constants.SUCCESS_REG_MESSAGE);
				return Constants.SUCCESS;
			}
			return Constants.FATAL;
		} catch (Exception e) {
			logger.error(e);
			return Constants.FATAL;
		}
	}
}
